<template>
  <el-form-item label="兑奖方式" class="exchange_type" :prop="ProxyPropOption.type">
    <el-radio-group v-model="props.model[ProxyOption.type]">
      <el-radio :label="1">兑奖码</el-radio>
      <el-radio :label="2" disabled>线下邮寄(敬请期待)</el-radio>
    </el-radio-group>
  </el-form-item>
  <el-form-item label="兑奖码" class="exchange_code_type" :prop="ProxyPropOption.code_type">
    <el-radio-group v-model="props.model[ProxyOption.code_type]">
      <el-radio :label="1">系统自动生成</el-radio>
      <el-radio :label="2">导入兑换码</el-radio>
      <el-upload></el-upload>
    </el-radio-group>
  </el-form-item>
  <el-form-item v-show="props.model[ProxyOption.code_type] === 2" :prop="ProxyPropOption.file_code">
    <el-upload ref="upload" v-model:file-list="fileList" class="upload-demo" accept=".xlsx,.xls,.csv" :limit="1"
      :on-exceed="handleExceed" :on-remove="handRemove" :before-upload="handBeforeUpload" :http-request="onHttpRequest">
      <el-button type="primary">{{ props.model[ProxyOption.file_code] ? '重新上传' : '点击上传' }}</el-button>
      <template #tip>
        <div class="el-upload__tip">导入兑奖码不能重复，文件不超过500kb</div>
      </template>
    </el-upload>
    <el-progress v-show="percentage" :percentage="percentage" color="#67c23a" :stroke-width="1" :format="() => ''" />
    <el-button type="primary" link class="download_template" @click="downloadTemplate" >下载模版</el-button>
  </el-form-item>
  <el-form-item class="exchange_date exchange_item" :prop="ProxyPropOption.date">
    <template #label>
      <el-popover
        placement="top-start"
        :width="270"
        trigger="hover"
        content="若未填写兑奖期限，则默认为永久有效"
      >
        <template #reference>
          <span class="exchange_date_label" >
            <el-icon><InfoFilled color="#E3E3E3"/></el-icon>
            <span>兑奖期限</span>
          </span>
        </template>
      </el-popover>
    </template>
    <el-date-picker v-model="props.model[ProxyOption.date]" type="datetimerange" format="YYYY-MM-DD HH:mm:ss"
      value-format="YYYY-MM-DD HH:mm:ss" range-separator="—" start-placeholder="开始时间" end-placeholder="结束时间"
      :default-time="defaultTime()" :disabledDate="disabledDataFun">
    </el-date-picker>
  </el-form-item>
  <el-form-item label="兑奖须知">
    <el-input v-model="props.model[ProxyOption.desc]" clearable show-word-limit placeholder="请保证获奖数据真实有效！" rows="3"
      type="textarea" maxlength="500" resize="none" />
  </el-form-item>
  <UploadFailDialog v-model="dialogVisible" :data="dialogData" />
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch } from 'vue'
import { UploadProps, UploadUserFile, UploadInstance, UploadRawFile, UploadRequestOptions, ElMessage } from 'element-plus'
import { genFileId } from 'element-plus'
import UploadFailDialog from './UploadFailDialog.vue'
import { defaultTime, downloadFile } from "@/utils/utils"
import { uploadFile2 } from '@/api/common'
import { importExChangeCode } from '@/api/smartMarketing/fissionDrainage'

const props = withDefaults(defineProps<Props>(), {
  model: () => ({}),
  options: () => ({}),
  propOption: () => ({}),
  rulePadStart: '',
  rewardList: () => ([]),
  basicDate: () => ({})
})

const disabledDataFun = (time: any) => {
  if (props.basicDate.period_type === 2) {
    return time.getTime() < +new Date(props.basicDate?.effect_date?.[0]) - (8.64e7 - 1)
  }
  return time.getTime() < Date.now() - 8.64e7
}

// 默认字段名
const ProxyOption = computed(() => ({
  type: props.options?.type ?? 'exchange_usage_type', // 兑奖方式
  code_type: props.options?.code_type ?? 'exchange_code_type', // 兑奖码
  file_code: props.options?.file_code ?? 'exchange_file_code', // 兑奖码文件
  date: props.options?.date ?? 'exchange_date', // 兑奖期限
  desc: props.options?.desc ?? 'exchange_desc', // 兑奖须知
  stock: props.options?.stock ?? 'reward_stock', // 库存数量
}))

const createRulePropName = (propName?: string, normalPropName?: string) => {
  return propName ?? `${props.rulePadStart}${normalPropName}`
}

// 默认校验的方式,并不会去用props.model的值做校验， 而是使用form组件的model的取值,校验名称会默认使用rulePadStart拼接的字段名
const ProxyPropOption = computed(() => ({
  type: createRulePropName(props.propOption.type, ProxyOption.value.type), // 兑奖方式
  code_type: createRulePropName(props.propOption.code_type, ProxyOption.value.code_type), // 兑奖码
  file_code: createRulePropName(props.propOption.file_code, ProxyOption.value.file_code), // 兑奖码
  date: createRulePropName(props.propOption.date, ProxyOption.value.date), // 兑奖期限
  desc: createRulePropName(props.propOption.desc, ProxyOption.value.desc), // 兑奖须知
}))

/* ============================上传文件-start============================ */
const fileList = ref<UploadUserFile[]>((() => {
  if (props.model.exchange_file_name && props.model.exchange_file_url) {
    return [{
      status: "success",
      name: props.model.exchange_file_name,
      url: props.model.exchange_file_url
    }]
  } else {
    return []
  }
})())

const upload = ref<UploadInstance>()
const dialogVisible = ref<boolean>(false)
const dialogData = reactive<any[]>([])

// 超出时删除上一个
const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  handRemove()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
  upload.value!.submit()
}
const handRemove = () => {
  percentage.value = 0
  props.model[ProxyOption.value.file_code] = ''
}

watch(() => props.model[ProxyOption.value.stock], (val) => {
  if (props.model[ProxyOption.value.file_code] && props.model[ProxyOption.value.code_type] === 2) {
    clearFiles()
    ElMessage.warning('请重新上传兑换码文件')
  }
})
const handBeforeUpload = (rawFile: UploadRawFile) => {
  const type = ['xls', 'xlsx', 'csv']
  const filetype = rawFile.name.split('.').pop() ?? ''
  if (!type.includes(filetype)) {
    ElMessage.warning('请上传xls、xlsx、或csv文件!')
    return false
  }
  if (rawFile.size > (500 * 1024)) {
    ElMessage.warning('文件大小不能超过500k!')
    return false
  }
  return true
}
// 进度条
const percentage = ref(0)

const onUploadProgress = (progressEvent: any) => {
  percentage.value = Math.floor((progressEvent.loaded * 100) / progressEvent.total)
}

// 自定义上传
const onHttpRequest = async (options: UploadRequestOptions) => {
  try {
    // 上传
    const res = await uploadFile2({
      file: options.file,
      fileName: options.file.name
    }, { onUploadProgress, noNeedLoading: true })
    // 校验

    const params = {
      current: {
        id: props.model.id,
        code: res.code,
        stock_num: props.model[ProxyOption.value.stock]
      },
      codes: props.rewardList.map(item => ({
        id: item.id,
        code: item[ProxyOption.value.file_code],
        stock_num: props.model[ProxyOption.value.stock]
      }))
    }
    const importRes = await importExChangeCode(params)
    if (importRes.success) {
      props.model[ProxyOption.value.file_code] = res.code
      return
    }
    percentage.value = 0
    upload.value!.clearFiles()
    handRemove()
    if (!importRes.num_match) return ElMessage.error('导入兑奖码不等于奖品数量')
    dialogVisible.value = true
    dialogData.splice(0)
    dialogData.push(...(importRes.err_lines ?? []))
  } catch {
    handRemove()
    clearFiles()
  }
}
const clearFiles = () => {
  props.model[ProxyOption.value.file_code] = ''
  upload.value!.clearFiles()
  percentage.value = 0
}

// 下载模板默认地址
const downloadTemplate = () => {
  downloadFile('//static.scrm.keyid.cn/keyid-scrm-server/template/%E5%85%91%E5%A5%96%E7%A0%81%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx')
}

/* ============================上传文件-end============================ */


interface Props {
  model: object | any,
  // 自定义校验
  options?: OptionsOption,
  // 自定义校验的方式
  propOption?: OptionsOption,
  // 校验的字符串名称的头部拼接字段名
  rulePadStart?: string,
  rewardList: any[],
  basicDate?: any
}
interface OptionsOption {
  type?: string, // 兑奖方式
  code_type?: string, // 兑奖码
  file_code?: string, // 兑奖码
  date?: string, // 兑奖期限
  desc?: string, // 兑奖须知
  stock?: string, // 库存数量
}
</script>

<style lang="scss" scoped>
.exchange_type,
.exchange_code_type {
  margin-bottom: 0px;
}

.exchange_type :deep(.el-form-item__error) {
  padding-top: 0;
  top: 26px;
}

.exchange_date {
  margin-top: 18px;
}

.exchange_item {
  margin-bottom: 16px;
}

.el-upload__tip {
  line-height: 14px;
  margin-top: 0;
  margin: 8px 0;
  color: #969696;
  font-size: 12px;
  font-size: 12px;
  font-family: PingFangSC-Regular, PingFang SC;
}

:deep(.el-upload-list) {
  margin: 0;

  .el-upload-list__item {
    padding: 5px 12px;
    box-sizing: border-box;
    background-color: #F5F5F5;
    border-radius: 2px;
    line-height: normal;
    margin-bottom: 0;

    .el-upload-list__item-name {
      padding: 0;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #585858;

    }

    .el-icon--close-tip {
      display: none !important;
    }

    .el-icon--close {
      right: 12px;
    }

    .el-upload-list__item-status-label {
      right: 12px;
    }

    &:hover {
      .el-icon--close {
        display: block !important;
      }
    }
  }
}

:deep(.el-progress__text) {
  min-width: 0;
  margin-left: 0px;
}

.download_template {
  position: absolute;
  top: 6px;
  left: 108px;
}
.exchange_date_label {
  display: flex;
  align-items: center;
  cursor: pointer;
  .el-icon {
    margin-right: 2px;
  }
}
</style>